<template>
  <FIModel v-model="visible" title="明细设置" @close="closeClick" @confirm="saveFunc">
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      :searchNum="searchItemCount"
      v-model:form-value="state.query"
      :table-column="columns"
      :wrapperSpan="searchWrapperSpan"
      :showCollapse="false"
      :showBgColor="false"
      :queryAuth="false"
      @submit="getPostList(state.query.codesetCode)"
    >
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="itemCode" label="卖方名称">
          <FIInput v-model="state.query.itemCode" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="codesetCode" label="国内保理合同编号">
          <FIInput v-model="state.query.codesetCode" clearable />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <div class="margin-bottom20"></div>

    <FITable
      ref="tableRef"
      class="box-radius2"
      title="代码分类明细"
      :id="`result_${tableId}`"
      :showSaveModel="false"
      :data="dataList"
      primaryKey="itemId"
      height="300"
      v-model:columns="columns"
      :isLoading="isTableLoading"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      @row-add-save="addRowSave"
      @table-refresh="getPostList(state.query.codesetCode)"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      :settingConfig="settingConfig"
      checkMode="radio"
    >
      <template #bizType="{ scope }">
        <FISelect
          v-if="scope.row.isSelected"
          v-model="scope.row.bizType"
          valueCustom="value"
          :options="arr2"
          clearable
        />
        <span v-else>{{ scope.row.bizType }}</span>
      </template>
      <template #headerBtn>
        <FIPopconfirmBtn
          title="您是否确认保存选中数据吗？"
          buttonText="选择"
          beforePopText="请选择一条数据"
          :btn-binds="{ border: true, prefixIcon: 'icon-shanchu' }"
          :isVisible="!!checkedRows.length"
          @confirm="addRowSave"
        >
        </FIPopconfirmBtn>
        <FIPopconfirmBtn
         class="margin-left12"
          title="您是否确认取消选中数据吗？"
          buttonText="取消"
          beforePopText="请选择一条数据"
          :btn-binds="{ border: true, prefixIcon: 'icon-shanchu' }"
          :isVisible="!!checkedRows.length"
          @confirm="chanelRow"
        >
        </FIPopconfirmBtn>
      </template>
    </FITable>

    <template #footer
      >
      <!-- 自定义底部区域 -->
      <slot name="footer">
        <div class="dialog-footer">
          <FIButton @click="handleClose">关闭</FIButton>
          <!-- <FIButton type="primary" @click="handleConfirm"> 确定 </FIButton> -->
        </div></slot
      ></template
    >
  </FIModel>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch, toRaw } from 'vue'
import { useRouter } from 'vue-router'
import FIFormItem from '@/components/FIFormItem.vue'
import linkForm from './linkForm.vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FITable from '@/components/FITable/index.vue'
import FIInput from '@/components/FIInput.vue'
import FIForm from '@/components/FIForm.vue'
import FIModel from '@/components/FIModel.vue'
import FISelect from '@/components/FISelect/index.vue'
import { apiQueryCodeitem } from '@/api/common'
import { initSearchData } from '@/utils/common'
// import { apiRegist,apiQueryUserPostsWithDept} from '@/api/user'
import { apiQueryUserPostsWithDept, apideleteCodeitem, apiSaveCodeitem } from '@/api/configEnvMaint/index.ts'
import { useMessage } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
const emits = defineEmits(['close', 'update:postShow', 'refresh'])
const props = defineProps({
  // 圆角大小
  postShow: {
    type: Boolean,
    default: false,
  },
  editData: {
    type: Object,
    default: () => {
      return {}
    },
  },
})
const router = useRouter()
const linkShow = ref(false)
const linksform = ref(null)
const selectedlink = ref({})
const state = reactive({
  query: {
    // itemId:'',
    itemCode: '',
    codesetCode: '',
    dynamicParams: [],
    orderbyParams: [],
    current: 1,
    size: 10,
  },
  dataList: [],
})
const settingConfig = reactive({
  hidden: true, // 隐藏操作栏上所有内容
})
const searchWrapperSpan = 8
const register = reactive({
  codesetCode: '',
  userName: '',
  password: '',
  loginName: '',
  mobile: '',
  gender: '',
  email: '',
  businessPhone: '',
  jobNo: '',
  deptId: '',
})

const dataList = ref([])
const getPostList = (codesetCode) => {
  console.log(11111)
  const par = {
    codesetCode,
    itemCode: state.query.itemCode,
    current: 1,
    size: 10,
  }
  apiQueryUserPostsWithDept(par)
    .then((res) => {
      if (res.data.success) {
        dataList.value = res.data.data.result.map((item) => ({
          ...item,
          codesetCode: codesetCode, // 这里替换为你要添加的值
        }))
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      // 处理错误
    })
}
// 隐藏搜索项有值的个数
const searchItemCount = computed(() => {
  let filledCount = 0
  const outKeys = ['dynamicParams', 'orderbyParams', 'size', 'current']
  // 下面是从第三项起计算常规搜索条件有值个树
  // 获取state.query的所有keys
  const queryKeys = Object.keys(state.query).filter((key) => !outKeys.includes(key))
  if (queryKeys.length < 3) return 0
  // 从第三项开始计算
  queryKeys.slice(2).forEach((key) => {
    if (state.query[key] !== '' && state.query[key] !== null) {
      filledCount++
    }
  })
  return filledCount
})
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  // searchFn()
  getPostList(state.query.codesetCode)
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  // searchFn()
  getPostList(state.query.codesetCode)
}
const deleteRow = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.itemId) ids.push(item?.itemId)
    })
  isTableLoading.value = true
  apideleteCodeitem(ids)
    .then((res) => {
      isTableLoading.value = false
      // searchFn()
      getPostList(state.query.codesetCode)
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const isTableLoading = ref(false)
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
// 页面编码
const tableId = 'pageMaint'
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100],
})
const columns: Column[] = reactive([
  {
    label: '国内保理合同代码',
    prop: 'codesetCode',
    align: 'center',
    width: '180',
    // editable: false,
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '国内保理合同编码',
    prop: 'itemCode',
    align: 'center',
    width: '180',
    queryName: '',
    editable: true,
    // sortable: true,
    // filterable: true,
    readonly: true,
    modelValue: { inputValue: '' },
    editType: 'input',
    editConfig: {
      rules: { itemCode: [{ required: true }] },
    },
  },
  {
    label: '卖方名称',
    prop: 'itemCname',
    queryName: 'tedfa00.form_Cname',
    align: 'center',
    width: '180',
    editType: 'input',
    editable: true,
    // filterable: true,
    // sortable: true,
    sortValue: '',
    // modelValue: { inputValue: '', isBlank: false, notBlank: false },
    modelValue: { inputValue: '' },
    editConfig: {
      rules: { itemCname: [{ required: true, message: '请输入页面名称', trigger: 'blur' }] },
    },
  },
  {
    label: '业务品种',
    prop: 'remark',
    align: 'center',
    width: '180',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    editable: true,
    // filterable: true,
    modelValue: { inputValue: '' },
    // sortable: true,
    sortValue: '',
    editConfig: {
      rules: { remark: [{ required: false, message: '请输入备注', trigger: 'blur' }] },
    },
  },

  {
    label: '融资比例%',
    prop: 'itemStatus',
    align: 'center',
    width: '180',
    editable: true,
    // filterable: true,
    // sortable: true,
    editType: 'select',
    modelValue: [],
    configValueToLable: {
      list: [
        { value: '1', label: '是' },
        { value: '0', label: '否' },
      ],
    },
    editConfig: {
      rules: { isLinked: [{ required: true, message: '请输入是否连号', trigger: 'blur' }] },
      options: [
        { value: '1', label: '是' },
        { value: '0', label: '否' },
      ],

      selectBinds: {
        multiple: false,
        valueCustom: 'value',
      },
    },
  },
  {
    label: '合同起始日期',
    prop: 'sortId',
    align: 'center',
    width: '180',
    editable: true,
    // filterable: true,
    // sortable: true,
    modelValue: { inputValue: '' },
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    //   editConfig: {
    //     rules: { projectName: [{ required: true, message: '请输入所属项目', trigger: 'blur' }] },
    //   },
  },

  //   {
  //   label: '',
  //   prop: 'action',
  //   actionConfig: [
  //     // { id: 'delete', type: 'delete' },
  //     // { id: 'b5555', type: 'add' },
  //     { id: 'action_link', type: 'action_link' },
  //     { id: 'b5555', type: 'add' },
  //   ],
  // },
])

const checkedRows = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
let visible: any = computed({
  get() {
    return props.postShow
  },
  set(val) {
    emits('update:postShow', val)
  },
})
const handleAction = (item, rowData, butoninfo) => {
  console.log(item, rowData, butoninfo)
  // isVisible.value=true
  linkShow.value = true
  selectedlink.value = rowData
  // globalMethod('777')
}
const registerRules = reactive({
  loginName: [{ required: true, message: '此为必填项', trigger: 'blur' }],
})
const addRowSave = (data) => {

  // router.push('/cfg/receivableMaint')
  router.push({name: 'processMaint'})
  // handleSave(data, 'add')
  // emits('refresh')
}
const tableRef = ref(null)
const chanelRow = () => {
  tableRef.value.addRowCancel()
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  console.log('save', checkedRows.value)
  const data = checkedRows.value.map((item) => ({
    ...item,
    codesetCode: state.query.codesetCode, // 这里替换为你要添加的值
  }))
  apiSaveCodeitem(data)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        // saveSuccessful.value = true
        tableRef.value.clearSelection()
        getPostList(state.query.codesetCode)
        // searchFn()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const searchFn = (type?: string, columnsVal?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns

  if(type == 'page'){
    state.query.current = pageConfig.currentPage
  }else{
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  apiRequestPost('/rm2/buttonMaint/query', state.query)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        const tempArr = res.data.data.result
        // tempArr.forEach((item: any, index) => {
        //   item.dynamicActionConfig = [
        //     { id: 'delete', type: 'delete', hidden: true, disabled: true },
        //     { id: 'add', type: 'add', disabled: false },
        //   ]
        // })
        state.dataList = tempArr
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const options = ref([
  { label: '男', value: '1' },
  { label: '女', value: '0' },
])
const closeClick = () => {
  //  linkShow.value = false
  tableRef.value.addRowCancel()
  console.log(selectedlink, 111)
  if (Object.keys(selectedlink.value).length > 0) {
    // linkShow.value = false
    selectedlink.value = {}
    // linksform.value.chanelRow()
    linkShow.value = false
  }
  emits('update:postShow', false)
}
const handleClose = () => {
  //  linkShow.value = false
  tableRef.value.addRowCancel()
  if (Object.keys(selectedlink.value).length > 0) {
    // linkShow.value = false
    // linksform.value.chanelRow()
    linkShow.value = false
  }
  emits('update:postShow', false)
}
const selectData = (val, name) => {
  // orgSelect.label = name
  register.deptId = val.value
}
// const saveFunc = () =>{
//   apiRegist(toRaw(register))
//   .then((res) => {
//     if(res.data.success){
//       useMessage().success(res.data.message)
//       // refresh

//     }
//   })
//   .catch((error: any) => {

//   })
// }
const clearTaleble = () => {
  // state.dataList=[]
  tableRef.value.addRowCancel()
}
watch(
  () => props.editData,
  (newValue) => {
    console.log(newValue)
    if (newValue.codesetCode) {
      console.log(newValue, 9999999999)
      state.query.codesetCode = newValue.codesetCode
      getPostList(newValue.codesetCode)
    }
  }
)
defineExpose({
  chanelRow,
})
const arr2 = ref([])
const getProjectname = () => {
  apiQueryCodeitem({ codesetCode: 'rm.bizType' }).then((res) => {
    if (res.data.success) {
      Array.isArray(res.data.data) &&
        res.data.data.forEach((item) => {
          // item.label = item.moduleCname2
          item.label = `【${item.itemCode}】${item.itemCname}`
          item.value = item.itemCode
        })
      if (Array.isArray(res.data.data)) {
        const newArray = res.data.data.map((item) => ({
          label: `【${item.itemCode}】${item.itemCname}`,
          value: item.itemCode,
        }))
        arr2.value = newArray
      }
    }
  })
}
onMounted(() => {
  getProjectname()
})
</script>
<style lang="less" scoped></style>
